3-Spring Data JPA
👻 中文文档
本文简单介绍下在Java中使用JPA工具进行CRUD完成开发,不涉及底层,旨在如何使用
Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA-based (Java Persistence API) repositories. It makes it easier to build Spring-powered applications that use data access technologies.
Implementing a data access layer for an application can be quite cumbersome. Too much boilerplate code has to be written to execute the simplest queries. Add things like pagination, auditing, and other often-needed options, and you end up lost.
Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces using any number of techniques, and Spring will wire it up for you automatically. You can even use custom finders or query by example and Spring will write the query for you!
Spring Data JPA 是 Spring Data 项目的一部分,它提供了一种简化的数据访问方式,用于与关系型数据库进行交互。它基于 Java Persistence API(JPA) 标准,并提供了一套简洁的 API 和注解,使开发人员能够通过简单的 Java 对象来表示数据库表,并通过自动生成的 SQL 语句执行常见的 CRUD 操作。Spring Data JPA 通过封装 JPA 的复杂性,简化了数据访问层的开发工作,使开发人员能够更专注于业务逻辑的实现。它还提供了丰富的查询方法的定义、分页和排序支持、事务管理等功能,使开发人员能够更方便地进行数据访问和操作。
spirng data jpa是spring提供的一套简化JPA开发的框架,按照约定好的规则进行方法命名去写dao层接口,就可以 在不写接口实现的情况下,实现对数据库的访问和操作。同时提供了很多除了CRUD之外的功能,如分页、排序、复杂查 询等等。
1.依赖导入
<dependency>导入jpa依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.Spring Data repository
Spring Data repository 抽象的中心接口是 Repository。它把要管理的 domain 类以及 domain 类的ID类型作为泛型参数。这个接口主要是作为一个标记接口,用来捕捉工作中的类型,并帮助你发现扩展这个接口的接口。 CrudRepository 和 ListCrudRepository 接口为被管理的实体类提供复杂的CRUD功能。
CrudRepository 接口
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity); // 保存实体
Optional<T> findById(ID primaryKey); // 根据ID查询
Iterable<T> findAll(); // 全查询
long count(); // 返回实体数量
void delete(T entity); // 根据实体删除
boolean existsById(ID primaryKey); //根据ID判断实体是否存在
// … more functionality omitted.
}
在Java中,我们常用的Repository就是JpaRepository,设计Dao接口继承JpaRepository,托管CRUD操作。
前提: 导入XML依赖,创建Entiy实体,创建Dao接口
public class User{
String name;
String sex;
}
public interface UserDao extends JpaRepository<User, String>{
}
通过这种方式,就可以在Dao中声明Query进行数据库操作了。
JpaRepository自带CRUD源码:
@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
List<T> findAll();
List<T> findAll(Sort var1);
List<T> findAllById(Iterable<ID> var1);
<S extends T> List<S> saveAll(Iterable<S> var1);
void flush();
<S extends T> S saveAndFlush(S var1);
void deleteInBatch(Iterable<T> var1);
void deleteAllInBatch();
T getOne(ID var1);
<S extends T> List<S> findAll(Example<S> var1);
<S extends T> List<S> findAll(Example<S> var1, Sort var2);
}